package com.sm.honkon.ui.activity

import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import au.com.safie.user.app.util.CacheUtil
import com.blankj.utilcode.util.ToastUtils
import com.sm.honkon.R
import com.sm.honkon.app.MyMqttService
import com.sm.honkon.app.base.BaseActivity
import com.sm.honkon.app.ext.getTimeFormat
import com.sm.honkon.app.utils.SerialPortUtil
import com.sm.honkon.data.bean.ControlLogCatEntity
import com.sm.honkon.data.bean.CustomerEntity
import com.sm.honkon.data.bean.HandlerEntity
import com.sm.honkon.databinding.ActMainBinding
import com.sm.honkon.ui.model.MainViewModel
import kotlinx.android.synthetic.main.act_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : BaseActivity<MainViewModel, ActMainBinding>() {
    override fun layoutId(): Int = R.layout.act_main
    val curCustomerEntity = MutableLiveData<CustomerEntity?>()
    val curHandlerEntity = MutableLiveData<HandlerEntity?>()
    val controlLogCat = MutableLiveData<ControlLogCatEntity?>()

    override fun initView(savedInstanceState: Bundle?) {
        /*requestWindowFeature(Window.FEATURE_NO_TITLE)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
        )
        if (supportActionBar != null) {
            supportActionBar?.hide()
        }*/
        SerialPortUtil.openSrialPort()
        MyMqttService.startService(this);
        lifecycleScope.launch(Dispatchers.Default) {
            while (true) {
                delay(1_000)
                appViewModel.dateLiveData.postValue(
                    System.currentTimeMillis().getTimeFormat("yyyy/MM/dd hh:mm")
                )
            }

        }
        host_fragment.findNavController().runCatching {
            graph = when {
                CacheUtil.isLogin() -> {
                    navInflater.inflate(R.navigation.main_navation)
                }
                else -> {
                    val hasAdmin = CacheUtil.getUser() != null
                    val loginGraph = navInflater.inflate(R.navigation.login_navation)
                    loginGraph.startDestination =
                        if (hasAdmin) R.id.loginFragment else R.id.signupFragment
                    loginGraph
                }
            }
        }.onFailure {
            ToastUtils.showShort(it.message)
        }
    }

    override fun onDestroy() {
        MyMqttService.stopService(this);
        super.onDestroy()
    }
}